<?php
/**
 * Created by PhpStorm.
 * User: 户学
 * Date: 2018/5/29
 * Time: 11:30
 */

use vod\Request\V20170321\CreateUploadVideoRequest;
use vod\Request\V20170321\RefreshUploadVideoRequest;
use vod\Request\V20170321 as vod;
use OSS\OssClient;
use OSS\Core\OssException;

include_once dirname(dirname(dirname(dirname(dirname((__FILE__))))))."/".'api/video/aliyun-php-sdk-core/Config.php';
require_once dirname(dirname(dirname(dirname(dirname((__FILE__))))))."/". 'api/video/aliyun-oss-php-sdk-2.2.4/autoload.php';

include_once dirname(dirname(dirname(dirname(dirname((__FILE__))))))."/".'api/video/aliyun-php-sdk-core/Profile/DefaultProfile.php';
include_once dirname(dirname(dirname(dirname(dirname((__FILE__))))))."/".'api/video/aliyun-php-sdk-vod/vod/Request/V20170321/CreateUploadVideoRequest.php';

class Publics extends M_Controller
{
    private $accessKeyId = 'LTAIEvlPaoHFZQNK';                    // 您的AccessKeyId

    private $accessKeySecret = 'Us5ShPEqXzVPCibT4qZvvYsQZAE7AD';            // 您的AccessKeySecret

//    private $localFile = 'D:\c741af1623e463864fe46ac038cc8021.mp4';   // 需要上传到VOD的本地视频文件的完整路径
    private $localFile = 'D:\00004.mts';   // 需要上传到VOD的本地视频文件的完整路径

    public function main(){
        // 重置页数和统计
        IS_POST && $_GET['page'] = $_GET['total'] = 0;

        // 根据参数筛选结果
        $param = $this->input->get(NULL, TRUE);
        unset($param['s'], $param['c'], $param['m'], $param['d'], $param['page']);


        list($data, $total, $param,$nogroud,$ground)	= $this->_limit_page(); // 数据库中分页查询
        $pagetotal = $this->db->select("count(*) as count")->get("public_class")->row_array();
        $pagetotal  = $pagetotal['count'];
        $id = (int)$param['id'];



        $this->template->assign(array(
            'list'=>$data,
            'total' => $total,
            "noground"=>$nogroud,
            "ground"=>$ground,
            'param' => $param,
            'stages'=>array("一年级","二年级","三年级","四年级","五年级","六年级","初一","初二","初三","高一","高二","高三"),
            'subjects'=>array("语文","数学","英语","物理","化学","生物","政治","历史","地理"),
            "course_type"=>array("1V4","1V1","免费试听","公开课","专题课"),
            'auser' => $this->db->where('id', $id)->get('public_class')->row_array(),
            'pages'	=> $this->get_pagination(dr_url('admin/publics/main', array(
                'uid' => $id,
                'total' => $total,
                'search' => IS_POST ? 1 : $this->input->get('search')
            )), $pagetotal)
        ));
        $this->template->display('video/index.html');
    }

    public function add(){
        if(IS_POST){
            $data = $this->input->get_post('data');
//            print_r($data);print_r($_POST);exit;
//            if(empty($data['name'])){
//                $this->msg('教师姓名不能为空');
//            }
            if(empty($data['title'])){
                $this->msg('标题不能为空');
            }
            if(empty($data['content'])){
                $this->msg('内容不能为空');
            }
            $course = $this->input->get_post("course");
            if(empty($course)){
                $this->msg('课程信息不能为空');
            }

            $arr = explode('/',$course);
            $course_type = $arr[0];
            $grade = $arr[1];
            $subject = $arr[2];
            $img = $this->input->get_post("upload_img");
            $sel_price = $this->input->get_post("sel_price");
            $keywords = $this->input->get_post("sel_keywords");
            $del_price = $this->input->get_post("del_price");
            $subtype = $this->input->get_post("subtype");
            if($subtype == 1){
                $data['is_ground'] = 1;
            }

            $data['addtime'] = time();
            $data['grade'] = $grade;
            $data['subject'] = $subject;
            $data['keywords'] = $keywords;
            $data['course_type'] = $course_type;
            $data['course_price'] = $sel_price;
            $data['market_price'] = $del_price;
            $data['cover'] = $img;
            $result = $this->db->insert('public_class',$data);
            $class_id = $this->db->insert_id();
            if($result){
                if($course_type == "录播课"){
                    $this->template->assign(array(
                        "class_id"=>$class_id,
                        "title"=>$data['title'],
                        "content"=>$data['content'],
                    ));
                    $this->template->display('video/add_video.html');
                    exit;
                }else{
                    $this->admin_msg('添加公开课成功', dr_url(APP_DIR.'/'.$this->router->class.'/main', $this->post_param), 1);
                }
            }
        }
        $this->template->assign(array(
            'name'=>'添加公开课',
            'stages'=>array("一年级","二年级","三年级","四年级","五年级","六年级","初一","初二","初三","高一","高二","高三"),
            'subjects'=>array("语文","数学","英语","物理","化学","生物","政治","历史","地理"),
        ));
        $this->template->display('video/add.html');
    }
    //删除课程
    public function del(){
        $id = $this->input->get_post('id');
        $data = $this->db->where("id",$id)->get("public_class")->row_array();
        if ($data['is_ground']==1){
            $this->msg('视频请先下架才可删除');
            exit;
        }
        if(empty($data)){
            $this->msg("课程已经删除或者不存在");
        }
        //$result = $this->db->where("id",$id)->update("public_class",array("is_del"=>0));
        $this->db->trans_start();
        $this ->db -> where("id",$id)->delete("public_class");//真实删除
        $result = $this ->db -> where("class_id",$id)->delete("class_video");
        $this->db->trans_complete();

        if($result){
            $this->admin_msg('删除课程成功', dr_url(APP_DIR.'/'.$this->router->class.'/main', $this->post_param), 1);
        }
    }

    //添加视频课程
    public function addvideo(){
        $class_id = $this->input->get_post("class_id");
        $title = $this->input->get_post("title");
        $videoid = $this->input->get_post('videoid');
        if(empty($class_id) || empty($title)){
            $this->msg("参数缺少");
        }
        $param = array(
            "title"=>$title,
            "videoid"=>$videoid,
            "class_id"=>$class_id,
            "addtime"=>time()
        );
        $result = $this->db->insert("class_video", $param);
        if($result){
            $this->admin_msg('添加录播课成功', dr_url(APP_DIR.'/'.$this->router->class.'/main', $this->post_param), 1);
        }
    }
    public function edit(){
        $id = $this->input->get_post('id');
        $data = $this->db->where('id', $id)->get('public_class')->row_array(); //预设资料

        if(empty($data)){
            $this->msg('改课程不存在');
        }
        if(IS_POST){
            $data = $this->input->get_post('data');

            if(empty($data['title'])){
                $this->msg('标题不能为空');
            }
            if(empty($data['content'])){
                $this->msg('内容不能为空');
            }
            $course_type = $this->input->get_post("course_type");
            $grade = $this->input->get_post('grade');
            $keywords = $this->input->get_post('sel_keywords');
            $subject = $this->input->get_post('subject');
            $img = $this->input->get_post("upload_img");
            $sel_price = $this->input->get_post("sel_price");
            $del_price = $this->input->get_post("del_price");
            $del_sort = $this->input->get_post("del_sort");

            $data['keywords'] = $keywords;
            $data['course_price'] = $sel_price;
            $data['market_price'] = $del_price;
            $data['market_sort'] = $del_sort;
            $data['addtime'] = time();
            $data['grade'] = $grade;
            $data['subject'] = $subject;
            $data['course_type'] = $course_type;



            if(!empty($img)){
                $data['cover'] = $img;
            }
            if($course_type == '录播课'){
                if(empty($data['name'])){
                        $this->msg('教师姓名不能为空');
                }
            }
            $result = $this->db->where('id',$id)->update('public_class',$data);
            if($result){
                $this->admin_msg('修改公开课成功', dr_url(APP_DIR.'/'.$this->router->class.'/main', $this->post_param), 1);
            }
        }
        $this->template->assign(array(
            'data'=>$data,
            'name'=>'公开课修改',
            'stages'=>array("一年级","二年级","三年级","四年级","五年级","六年级","初一","初二","初三","高一","高二","高三"),
            'subjects'=>array("语文","数学","英语","物理","化学","生物","政治","历史","地理"),
        ));
        $this->template->display('video/public_edit.html');
    }
    public function view(){
        $id = $this->input->get_post('id');
        $data = $this->db->where('id', $id)->get('public_class')->row_array(); //预设资料

        if(empty($data)){
            $this->msg('改课程不存在');
        }
        if(IS_POST){
            $data = $this->input->get_post('data');

            if(empty($data['title'])){
                $this->msg('标题不能为空');
            }
            if(empty($data['content'])){
                $this->msg('内容不能为空');
            }
            $course_type = $this->input->get_post("course_type");
            $grade = $this->input->get_post('grade');
            $subject = $this->input->get_post('subject');
            $img = $this->input->get_post("upload_img");

            $data['addtime'] = time();
            $data['grade'] = $grade;
            $data['subject'] = $subject;
            $data['course_type'] = $course_type;

            if(!empty($img)){
                $data['cover'] = $img;
            }
            if($course_type == '录播课'){
                if(empty($data['name'])){
                    $this->msg('教师姓名不能为空');
                }
            }
            $result = $this->db->where('id',$id)->update('public_class',$data);
            if($result){
                $this->admin_msg('修改公开课成功', dr_url(APP_DIR.'/'.$this->router->class.'/main', $this->post_param), 1);
            }
        }
        $this->template->assign(array(
            'data'=>$data,
            'name'=>'公开课修改',
            'stages'=>array("一年级","二年级","三年级","四年级","五年级","六年级","初一","初二","初三","高一","高二","高三"),
            'subjects'=>array("语文","数学","英语","物理","化学","生物","政治","历史","地理"),
        ));
        $this->template->display('video/view_class.html');
    }





    //上架 下架
    public function moveground(){
        $ground = $this->input->get_post('ground');
        $course_id = $this->input->get_post("course_id");
        $data = $this->db->where("id",$course_id)->get("public_class")->row_array();
        if(empty($data)){
            $this->msg('该课程已经删除或者不存在');
        }
        $para = array();
        $data = array();
        if($ground){
            $para = array("is_ground"=>0);
            $data['message'] = "下架成功";
        }else{
            $para = array("is_ground"=>1);
            $data['message'] = "上架成功";
        }
        $result = $this->db->where("id",$course_id)->update("public_class",$para);
        if($result){
            $data['status'] = 1;
            $data['msg'] = "修改成功";
        }else{
            $data['status'] = 0;
            $data['msg'] = "修改失败";
        }
        echo json_encode($data);exit;
    }
    //操作 课程上架  课程下架
    public function operate(){
        $opid = $this->input->get_post("opid");
        $courses = $this->input->get_post("courses");
        if(empty($courses) || !isset($opid)){
            $this->msg("参数错误");
        }
        $ss = "";
        $va = 0;
        if($opid == 0 || $opid == 1){
            $ss = "is_ground";
            $va = $opid;
        }else{
            $ss = "is_del";
            $va = 0;
        }
        $param = array();
        $arr = explode(",", $courses);
        $flag = false;
        if(count($arr)>0){
            foreach($arr as $key=>$cid){
                $flag = $this->db->where("id",$cid)->update("public_class",array($ss=>$va));
            }
        }
        $data = array();
        if($flag){
            $data['status'] = 1;
            $data['msg'] = "批量操作成功";
        }else{
            $data['status'] = 0;
            $data['msg'] = "批量操作失败";
        }
        echo json_encode($data);exit;
    }
    //获取视频凭证
//    public function getAuthorvideo(){
//        $param = $_POST;
//        $param['SignatureNonce'] = create_uuid();
//        $param['Timestamp'] = date("Y-m-dTH:i:sz",time());
//        $param['SignatureMethod'] = "HMAC-SHA1";
//
//        $result = send_posts("http://vod.cn-shanghai.aliyuncs.com",$param);
//        print_r($result);exit;
////        print_r($param);exit;
//    }

    //php 版本的视频上传
    public function uploadmyvideo(){
        try {
            // 初始化VOD客户端并获取上传地址和凭证
            $vodClient = init_vod_client($this->accessKeyId, $this->accessKeySecret);
            $createRes = create_upload_video($vodClient);

            // 执行成功会返回VideoId、UploadAddress和UploadAuth
            $videoId = $createRes->VideoId;
            $uploadAddress = json_decode(base64_decode($createRes->UploadAddress), true);
            $uploadAuth = json_decode(base64_decode($createRes->UploadAuth), true);

            // 使用UploadAuth和UploadAddress初始化OSS客户端
            $ossClient = init_oss_client($uploadAuth, $uploadAddress);
//            print_r($ossClient);exit;
            // 上传文件，注意是同步上传会阻塞等待，耗时与文件大小和网络上行带宽有关
//            $result = upload_local_file($ossClient, $uploadAddress, $this->localFile);
            $result = multipart_upload_file($ossClient, $uploadAddress, $this->localFile);
            var_dump($result);
            printf("Succeed, VideoId: %s", $videoId);

        } catch (Exception $e) {
            // var_dump($e);
            printf("Failed, ErrorMessage: %s", $e->getMessage());
        }
    }
    //上传视频
    public function uploadvideo(){
        $access_key_id = "LTAIEvlPaoHFZQNK";
        $access_key_secret = "Us5ShPEqXzVPCibT4qZvvYsQZAE7AD";
        $title = $this->input->get_post("title");
        $regionId = 'cn-shanghai';
        $profile = DefaultProfile::getProfile($regionId, $access_key_id, $access_key_secret);
        $client = new DefaultAcsClient($profile);
//
        $createResponse = $this->create_upload_video($client, $regionId, $title);
        //上传凭证
//        $refreshResponse = $this->refresh_upload_video($client, $regionId);

        echo json_encode($createResponse);exit;
    }
    private function create_upload_video($client, $regionId, $title = '') {
//        require_once dirname(dirname(dirname(dirname(dirname((__FILE__))))))."/".'api/video/aliyun-php-sdk-vod/vod/Request/V20170321/CreateUploadVideoRequest.php';
        $request = new CreateUploadVideoRequest();
        //视频源文件标题(必选)
//        $request->setTitle("视频标题");
        $request->setTitle($title);
        //视频源文件名称，必须包含扩展名(必选)
        $request->setFileName("文件名称.mov");
        //视频源文件字节数(可选)
        $request->setFileSize(0);
        //视频源文件描述(可选)
        $request->setDescription("视频描述");
        //自定义视频封面URL地址(可选)
        $request->setCoverURL("http://cover.sample.com/sample.jpg");
        //上传所在区域IP地址(可选)
        $request->setIP("127.0.0.1");
        //视频标签，多个用逗号分隔(可选)
        $request->setTags("标签1,标签2");
        //视频分类ID(可选)
        $request->setCateId(0);
        $response = $client->getAcsResponse($request);
        return $response;
    }

    /**
     * @param $client
     * @param $regionId
     * @return mixed
     */
    public function refresh_upload_video($client, $regionId) {
        require_once dirname(dirname(dirname(dirname(dirname((__FILE__))))))."/".'api/video/aliyun-php-sdk-vod/vod/Request/V20170321/RefreshUploadVideoRequest.php';
//        var_dump(dirname(dirname(dirname(dirname(dirname((__FILE__))))))."/".'api/video/aliyun-php-sdk-vod/vod/Request/V20170321/RefreshUploadVideoRequest.php');exit;
        $request = new RefreshUploadVideoRequest();
        //视频ID(必选)
        $request->setVideoId("视频ID");
        $response = $client->getAcsResponse($request);
        return $response;
    }

    //上传图片
    public function uploadImg(){

        $config['upload_path']      = './uploadfile/video/';
        $config['allowed_types']    = 'gif|jpg|png';
        $config['max_size']     = 1024*10;
        $config['max_width']        = 2000;
        $config['max_height']       = 2000;
        $config['file_name']  = time(); //文件名不使用原始名

        $this->load->library('upload', $config);
        if (!$this->upload->do_upload('img'))
        {
            $error = array('error' => $this->upload->display_errors());
            $result['msg'] = $error  ;
            $result['status'] = 0;

//            print_r($error);exit;
//            $this->load->view('upload_form', $error);
        }else
        {
            $data = array('upload_data' => $this->upload->data());
            $result = array();
            $result['img_url'] =   $config['upload_path'].$data['upload_data']['orig_name'];
            $result['status'] = 1;
//            echo json_encode($result);exit;
//            $this->load->view('upload_success', $data);
        }
        echo json_encode($result);exit;

    }

    private function _where(&$select) {

        $uid = (int)$this->input->get('id');
        $uid = $uid ? $uid : $this->uid;
        $search = $this->input->get('search');
        $ground = $this->input->get('ground');
        $grade = $this->input->get_post("grade");
        $subject = $this->input->get_post("subject");
        $course_type = $this->input->get_post("course_type");
        $name = $this->input->get_post("name");

        $cache_file = md5($this->duri->uri(1).$uid.$this->uid.SITE_ID.$this->input->ip_address().$this->input->user_agent()); // 缓存文件名称

        // 存在POST提交时，重新生成缓存文件
        if (IS_POST) {
            $data = $this->input->post('data');
            $this->cache->file->save($cache_file, $data, 3600);
            $search = 1;
            unset($_GET['page']);
        }
//        $select->where('id', $uid);
        $select->where("is_del",1);
        if(isset($ground)){
            $select->where(array('is_ground'=>$ground,"is_del"=>1));
        }
        if(!empty($grade)){
            $select->where('grade', $grade);
        }
        if(!empty($subject)){
            $select->where('subject', $subject);
        }
        if(!empty($course_type)){
            $select->where('course_type', $course_type);
        }
        if(!empty($name)){
            $select->where('title', $name);
            $select->or_where("id", $name);
        }

        // 存在search参数时，读取缓存文件
        if ($search == 1) {
            $data = $this->cache->file->get($cache_file);
            if (isset($data['start']) && $data['start'] && $data['start'] != $data['end']) {
                $data['end'] = $data['end'] ? $data['end'] : SYS_TIME;
                $select->where('logintime BETWEEN '.$data['start'].' AND '. $data['end']);
            }
        }
//        $data['id'] = $uid;
        $data['ground'] = $ground;
        $data['grade'] = $grade;
        $data['subject'] = $subject;
        $data['course_type'] = $course_type;
        return $data;
    }

    private function  _limit_page(){
        $page = max((int)$this->input->get_post('page'),1);
        $_total = (int)$this->input->get_post('total');
        $select = $this->db;
        $_param = $this->_where($select);
        if(!$_total){
            $arr = $this->db->select("count(*) as count")->get("public_class")->row_array();
            $_total = $arr['count'];
            if(!$_total){
//                return array(array(), 0 ,$_param);
                return array();
            }
        }
        //未上架的课程
        $no_ground = $this->db->select("count(*) as count")->where(array("is_ground"=>0,"is_del"=>1))->get("public_class")->row_array();
        $ground = $this->db->select("count(*) as count")->where(array("is_ground"=>1,"is_del"=>1))->get("public_class")->row_array();

        $result = $this->db
            ->limit(SITE_ADMIN_PAGESIZE, SITE_ADMIN_PAGESIZE * ($page - 1))
            ->order_by('id desc')
            ->get('public_class')
            ->result_array();
//        return array($result,$_total,$_param,$no_ground['count'],$ground['count']);
        return array($result,$_total,$_param,$no_ground['count'],$ground['count']);
    }

}